//fileManager.js
"use strict";

const fs = require("fs");
const path = require("path");

// 交互式文件管理器
// 步骤：
// 1) 提示要创建的文件夹，如：mkdir filedir
// 2) 提示要创建的文件，如：touch file.txt（会写入"hello node,"）
// 3) 提示要删除的文件，如：delete file.txt（删除后退出）

const STDIN = process.stdin;
STDIN.setEncoding("utf8");

let step = 0;
let targetDir = "";

function askCreateDir() {
	process.stdout.write("请输入要创建的文件夹：\n");
}

function askCreateFile() {
	process.stdout.write("请输入要创建的文件：\n");
}

function askDeleteFile() {
	process.stdout.write("请输入要删除的文件：\n");
}

function safeResolve(base, subPath) {
	const p = path.resolve(base, subPath);
	if (!p.startsWith(path.resolve(base))) {
		throw new Error("非法路径");
	}
	return p;
}

function handleCreateDir(line) {
	// 期望输入格式：mkdir filedir
	const parts = line.trim().split(/\s+/);
	if (parts.length !== 2 || parts[0].toLowerCase() !== "mkdir") {
		process.stdout.write("格式错误，请输入：mkdir 文件夹名\n");
		return;
}
	const dirName = parts[1];
	targetDir = path.resolve(process.cwd(), dirName);

	try {
		if (!fs.existsSync(targetDir)) {
			fs.mkdirSync(targetDir, { recursive: true });
		}
		process.stdout.write("文件夹创建成功！！\n");
		step = 1;
		askCreateFile();
	} catch (err) {
		process.stdout.write(`创建失败: ${err.message}\n`);
	}
}

function handleCreateFile(line) {
	// 期望输入格式：touch file.txt
	const parts = line.trim().split(/\s+/);
	if (parts.length !== 2 || parts[0].toLowerCase() !== "touch") {
		process.stdout.write("格式错误，请输入：touch 文件名\n");
		return;
}
	const fileName = parts[1];
	try {
		const filePath = safeResolve(targetDir, fileName);
		fs.writeFileSync(filePath, "hello node,");
		process.stdout.write("文件创建成功\n");
		step = 2;
		askDeleteFile();
	} catch (err) {
		process.stdout.write(`创建失败: ${err.message}\n`);
	}
}

function handleDeleteFile(line) {
	// 期望输入格式：delete file.txt
	const parts = line.trim().split(/\s+/);
	if (parts.length !== 2 || parts[0].toLowerCase() !== "delete") {
		process.stdout.write("格式错误，请输入：delete 文件名\n");
		return;
}
	const fileName = parts[1];
	try {
		const filePath = safeResolve(targetDir, fileName);
		if (fs.existsSync(filePath)) {
			fs.unlinkSync(filePath);
			process.stdout.write("删除成功，程序退出。\n");
		} else {
			process.stdout.write("文件不存在，程序退出。\n");
		}
		process.exit(0);
	} catch (err) {
		process.stdout.write(`删除失败: ${err.message}\n`);
		process.exit(1);
	}
}

STDIN.on("data", (chunk) => {
	const line = chunk.toString();
	if (step === 0) return handleCreateDir(line);
	if (step === 1) return handleCreateFile(line);
	if (step === 2) return handleDeleteFile(line);
});

askCreateDir();